package top.blueShark.template.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.blueShark.template.entity.SysMenu;
import top.blueShark.template.service.SysMenuService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/system/menu")
public class SystemMenuController {

	private static final Logger logger = LoggerFactory.getLogger(SystemMenuController.class);

	@Resource
	private SysMenuService sysMenuService;

	/**
	 * 获取菜单树数据
	 */
	@GetMapping("/list")
	public Map<String, Object> getMenuList() {
		logger.info("获取菜单树数据（真实接口）");
		//根据角色来获取菜单
		List<SysMenu> menuList = sysMenuService.getMenuTree();
		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", menuList);
		result.put("error", null);
		result.put("message", "ok");
		return result;
	}

	/**
	 * 判断菜单路径是否存在
	 */
	@GetMapping("/path-exists")
	public Map<String, Object> pathExists(@RequestParam(required = false) String path, @RequestParam(required = false) Integer id) {
		logger.info("校验菜单路径是否存在，path: {}, id: {}", path, id);
		boolean exists = sysMenuService.pathExists(path, id);
		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", exists);
		result.put("error", null);
		result.put("message", "ok");
		return result;
	}

	/**
	 * 判断菜单名称是否存在
	 */
	@GetMapping("/name-exists")
	public Map<String, Object> nameExists(@RequestParam(required = false) String name, @RequestParam(required = false) Integer id) {
		logger.info("校验菜单名称是否存在，name: {}, id: {}", name, id);
		boolean exists = sysMenuService.nameExists(name, id);
		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", exists);
		result.put("error", null);
		result.put("message", "ok");
		return result;
	}


	@PostMapping
	public Map<String, Object> addMenu(@RequestBody Map<String, Object> param) {
		logger.info("接收到添加菜单请求，参数：{}", param);

		SysMenu menu = new SysMenu();
		// 解析参数
		menu.setName((String) param.get("name"));
		menu.setPath((String) param.get("path"));

		// 校验菜单名称是否已存在（新增时id为null）
		if (sysMenuService.nameExists(menu.getName(), null)) {
			Map<String, Object> result = new HashMap<>();
			result.put("code", 1);
			result.put("data", null);
			result.put("error", null);
			result.put("message", "菜单名称已存在");
			return result;
		}

		// 校验菜单路径是否已存在（新增时id为null）
		if (sysMenuService.pathExists(menu.getPath(), null)) {
			Map<String, Object> result = new HashMap<>();
			result.put("code", 1);
			result.put("data", null);
			result.put("error", null);
			result.put("message", "路由地址已存在");
			return result;
		}

		menu.setComponent((String) param.get("component"));
		menu.setType((String) param.get("type"));
		menu.setStatus((Integer) param.get("status"));
		menu.setAuthCode((String) param.get("authCode"));
		// 你可以根据需要设置 pid、icon、orderNum、remark 等字段
		if (param.get("pid") == null) {
			menu.setPid(0); // 中文注释：如果前端没传pid，默认设为0
		} else {
			menu.setPid((Integer) param.get("pid"));
		}
		if (param.get("icon") != null) {
			menu.setIcon((String) param.get("icon"));
		}
		if (param.get("orderNum") != null) {
			menu.setOrderNum((Integer) param.get("orderNum"));
		}
		if (param.get("remark") != null) {
			menu.setRemark((String) param.get("remark"));
		}
		// 处理 meta 字段，转为 JSON 字符串存储
		Object meta = param.get("meta");
		if (meta != null) {
			try {
				ObjectMapper objectMapper = new ObjectMapper();
				String metaJson = objectMapper.writeValueAsString(meta);
				menu.setMetaJson(metaJson);
			} catch (Exception e) {
				logger.error("meta字段转JSON失败", e);
			}
		}

		sysMenuService.addMenu(menu);

		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", null);
		result.put("error", null);
		result.put("message", "添加成功");
		return result;
	}

	@PutMapping("/{id}")
	public Map<String, Object> updateMenu(@PathVariable Integer id, @RequestBody Map<String, Object> param) {
		logger.info("接收到更新菜单请求，id: {}, 参数：{}", id, param);

		SysMenu menu = new SysMenu();
		// ID直接从路径变量获取，不再从param中解析
		menu.setId(id);
		menu.setName((String) param.get("name"));
		menu.setPath((String) param.get("path"));

		// 校验菜单名称是否已存在（修改时传入当前菜单id）
		if (sysMenuService.nameExists(menu.getName(), menu.getId())) {
			Map<String, Object> result = new HashMap<>();
			result.put("code", 1);
			result.put("data", null);
			result.put("error", null);
			result.put("message", "菜单名称已存在");
			return result;
		}

		// 校验菜单路径是否已存在（修改时传入当前菜单id）
		if (sysMenuService.pathExists(menu.getPath(), menu.getId())) {
			Map<String, Object> result = new HashMap<>();
			result.put("code", 1);
			result.put("data", null);
			result.put("error", null);
			result.put("message", "路由地址已存在");
			return result;
		}

		menu.setComponent((String) param.get("component"));
		menu.setType((String) param.get("type"));
		menu.setStatus((Integer) param.get("status"));
		menu.setAuthCode((String) param.get("authCode"));

		if (param.get("pid") == null) {
			menu.setPid(0); // 中文注释：如果前端没传pid，默认设为0
		} else {
			menu.setPid((Integer) param.get("pid"));
		}
		if (param.get("icon") != null) {
			menu.setIcon((String) param.get("icon"));
		}
		if (param.get("orderNum") != null) {
			menu.setOrderNum((Integer) param.get("orderNum"));
		}
		if (param.get("remark") != null) {
			menu.setRemark((String) param.get("remark"));
		}
		// 处理 meta 字段，转为 JSON 字符串存储
		Object meta = param.get("meta");
		if (meta != null) {
			try {
				ObjectMapper objectMapper = new ObjectMapper();
				String metaJson = objectMapper.writeValueAsString(meta);
				menu.setMetaJson(metaJson);
			} catch (Exception e) {
				logger.error("meta字段转JSON失败", e);
			}
		}

		sysMenuService.updateMenu(menu); // 调用更新方法

		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", null);
		result.put("error", null);
		result.put("message", "更新成功");
		return result;
	}

	/**
	 * 删除菜单
	 */
	@DeleteMapping("/{id}")
	public Map<String, Object> deleteMenu(@PathVariable Integer id) {
		logger.info("删除菜单，id: {}", id);
		sysMenuService.deleteMenu(id);
		Map<String, Object> result = new HashMap<>();
		result.put("code", 0);
		result.put("data", null);
		result.put("error", null);
		result.put("message", "删除成功");
		return result;
	}
	
}